package shopping.controller;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import shopping.entity.ParentEntity;
import shopping.service.interfaces.ICommonService;
import shopping.util.ResultCode;
import shopping.util.ResultData;

import com.alibaba.fastjson.JSON;

/**
 * 公用方法
 * 
 * @author JiangHuiJun
 *
 */
@RequestMapping("common")
@Controller
public class CommonController {

	private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

	@Autowired
	ICommonService commService;

	/**
	 * 按id删除
	 * 
	 * @param id
	 * @param className
	 * @return
	 */
	@RequestMapping("/{className}/{id}/delete.action")
	@ResponseBody
	public ResultData deleteById(@PathVariable int id,@PathVariable String className) {
		ResultData resultData = new ResultData();
		try {
			Object object = commService.queryById(getClassName(className), id);
			if (object != null) {
				commService.deleteById((ParentEntity) object);
			} else {
				resultData.parse(ResultCode.DATE_NOT_FIND);
			}
		} catch (Exception e) {
			resultData.parse(ResultCode.SYSTEM_ERROR);
			logger.info(e.getMessage());
		}
		return resultData;
	}

	/**
	 * 插入
	 */
	@RequestMapping(value = "/{className}/save.action")
	@ResponseBody
	public ResultData save(@RequestParam String param,@PathVariable String className) {
		ResultData resultData = new ResultData();
		try {
			Object tObject = JSON.parseObject(param, getClassName(className));
			commService.save((ParentEntity) tObject);
		} catch (Exception e) {
			resultData.parse(ResultCode.SYSTEM_ERROR);
			logger.info(e.getMessage());
		}
		return resultData;
	}

	/**
	 * 更新
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{className}/update.action")
	@ResponseBody
	public ResultData Update(@RequestParam String param,@PathVariable String className) {
		ResultData resultData = new ResultData();
		try {

			ParentEntity newPOJO = JSON.parseObject(param, getClassName(className));
			logger.info("newPOJO:" + JSON.toJSONString(newPOJO));
			ParentEntity oldPOJO = (ParentEntity) commService.queryById(getClassName(className),newPOJO.getId());
			logger.info("oldPOJO:" + JSON.toJSONString(oldPOJO));
			if (oldPOJO == null) {
				resultData.parse(ResultCode.DATE_NOT_FIND);
				return resultData;
			}
			ConvertUtils.register(new DateConverter(null), java.util.Date.class);
			copyProperties(newPOJO, oldPOJO);// dest ori
			oldPOJO.setUpdateTime(new Date());
			logger.info("copynewPOJO:" + JSON.toJSONString(oldPOJO));
			commService.update(oldPOJO);
		} catch (Exception e) {
			resultData.parse(ResultCode.SYSTEM_ERROR);
			logger.info(e.getMessage());
		}
		return resultData;
	}

	/**
	 * 列表页面
	 * 
	 * @param className
	 * @return
	 */
	@RequestMapping("/{className}/list.htm")
	public String list(@PathVariable String className) {
		return className.toLowerCase() + "/list";
	}

	/**
	 * 添加页面
	 * 
	 * @param className
	 * @return
	 */
	@RequestMapping("/{className}/add.htm")
	public String add(@PathVariable String className) {
		return className.toLowerCase() + "/add";
	}

	/**
	 * 修改页面及数据展示
	 * 
	 * @param id
	 * @param className
	 * @param view
	 * @return
	 */
	@RequestMapping("/{className}/{id}/update.htm")
	public ModelAndView update(@PathVariable int id,@PathVariable String className, ModelAndView view) {
		try {
			Object object = commService.queryById(getClassName(className), id);
			view.addObject(className.toLowerCase(), object);
			view.setViewName(className.toLowerCase() + "/update");
		} catch (ClassNotFoundException e) {
			logger.info(e.getMessage());
		}
		return view;
	}

	/**
	 * 获取当前调用对象实例
	 * 
	 * @param className
	 * @return
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	private Class<ParentEntity> getClassName(String className)throws ClassNotFoundException {
		return (Class<ParentEntity>) Class.forName("shopping.entity."+ className);
	}

	private static void copyProperties(Object src, Object dest)throws Exception {

		List<Field> srcList = Arrays.asList(src.getClass().getDeclaredFields());
		List<Field> destList = Arrays.asList(dest.getClass().getDeclaredFields());
		// 遍历字段
		for (Field filed : srcList) {
			// 获取该字段的值
			boolean flag = false;
			filed.setAccessible(true);
			Object value = filed.get(src);
			if (value != null && !"".equals(value)) {
				for (Field f : destList) {
					if (f.getName().equals(filed.getName())) {
						flag = true;
						break;
					}
				}
				// 给该字段设值
				if (flag)
					filed.set(dest, value);
			}
		}
	}

}
